package com.autoagent.ai_live_master.webSocket.listener;

import com.autoagent.ai_live_master.common.event.WebSocketConnectionEvent;
import com.autoagent.ai_live_master.webSocket.service.WordCloudService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * WebSocket连接事件监听器
 * 监听WebSocket连接建立事件，发送定式话术
 */
@Slf4j
@Component
public class WebSocketConnectionEventListener {

    @Autowired
    private WordCloudService wordCloudService;

    /**
     * 监听WebSocket连接事件
     */
    @EventListener
    public void handleWebSocketConnectionEvent(WebSocketConnectionEvent event) {
        try {
            log.info("收到WebSocket连接事件，房间ID: {}, 连接类型: {}", event.getRoomId(), event.getConnectionType());
            
            // 发送定式话术
            wordCloudService.sendFormulaicScript(event.getRoomId());
            log.info("已发送定式话术，房间ID: {}, 连接类型: {}", event.getRoomId(), event.getConnectionType());
            
        } catch (JsonProcessingException e) {
            log.error("发送定式话术失败，房间ID: {}, 连接类型: {}, 错误: {}", 
                    event.getRoomId(), event.getConnectionType(), e.getMessage(), e);
        } catch (Exception e) {
            log.error("处理WebSocket连接事件失败，房间ID: {}, 连接类型: {}, 错误: {}", 
                    event.getRoomId(), event.getConnectionType(), e.getMessage(), e);
        }
    }
}
